package com.zzzzzz.content.article;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zzzzzz.account.signin.NoSuchOnlineUserException;
import com.zzzzzz.account.signin.OnlineService;
import com.zzzzzz.common.message.Message;
import com.zzzzzz.common.message.MessageIcon;
import com.zzzzzz.common.page.PageStart;
import com.zzzzzz.content.Constants;
import com.zzzzzz.content.ContentPictureService;
import com.zzzzzz.content.KindEditorUploadResult;
import com.zzzzzz.content.reply.ReplyService;
import com.zzzzzz.content.reply.ReplyView;
import com.zzzzzz.content.tag.NoSuchTagException;

@Controller
public class ArticleController {
	@Resource
	private ArticleService articleService;
	@Resource
	private ContentPictureService contentPictureService;
	@Resource
	private ReplyService replyService;
	@Resource
	private OnlineService onlineService;
	
	@RequestMapping(value = "/article/add", method = RequestMethod.GET)
	public String addPage(@ModelAttribute ArticleForm articleForm) {
		return "content/article/add";
	}
	
	@RequestMapping(value = "/article/add", method = RequestMethod.POST)
	public String add(Model model, @Valid ArticleForm articleForm, BindingResult bindingResult, RedirectAttributes redirectAttributes, Locale locale) throws NoSuchOnlineUserException, NoSuchTagException {
		if (bindingResult.hasErrors()) {
			return addPage(articleForm);
		}
		
		Long userId = onlineService.findUserId();
		try {
			Long topicId = articleService.add(userId, articleForm);
			return "redirect:/article/" + topicId;
		} catch (Exception e) {
			logger.warn("articleadd", e);
			redirectAttributes.addFlashAttribute(Message.error(MessageIcon.WARNING + "添加失败"));
			return "redirect:/article/add";
		}
	}
	
	@RequestMapping(value = "/article/upload", method = RequestMethod.POST)
	public @ResponseBody KindEditorUploadResult imageUpload(@RequestParam CommonsMultipartFile imgFile, HttpServletRequest request) {
		try {
			String fileName = contentPictureService.saveArticlePicture(imgFile);
			return new KindEditorUploadResult(0, request.getContextPath() + "/img/" + fileName);
		} catch (IOException e) {
			return new KindEditorUploadResult(1, "上传文件失败。");
		}
	}
	
	@RequestMapping(value="/article/{id}", method=RequestMethod.GET)
	public String view(@PathVariable Long id, @RequestParam(value = "start", defaultValue = "0", required = false) Integer start, HttpServletRequest request, Model model) throws Exception {
		ArticleView articleView = articleService.findViewById(id);
		if(articleView != null){
			articleService.plusLooks(id);
		}
		model.addAttribute("topicView", articleView);
		
		String replyListUrlEnd = "#replySpan";
		
		List<ReplyView> replyViewList = replyService.findByTopicId(id, Constants.CONTENT_DB_TYPE.CONTENT, start, PageStart.DEFAULT_OFFSET);
		Long replyViewListCount = replyService.findByTopicIdCount(id, Constants.CONTENT_DB_TYPE.CONTENT);
		PageStart replyViewListPageBar = new PageStart(start, PageStart.DEFAULT_OFFSET, replyViewListCount, "/topic/"+id, replyListUrlEnd);
		
		model.addAttribute("replyViewList", replyViewList);
		model.addAttribute("replyViewListCount", replyViewListCount);
		model.addAttribute("replyViewListPageBar", replyViewListPageBar.getPageBar());
		
		model.addAttribute("backUrl", URLEncoder.encode("/article/"+id+replyListUrlEnd, "UTF-8"));
		
		return "content/article/view";
	}
	
	private static final Logger logger = LoggerFactory.getLogger(ArticleController.class);
}
